package com.mall.service.impl;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.mall.config.ALiYunProperties;
import com.mall.service.FileUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Override
    public String uploadFile(MultipartFile file) {
        String url = "";
        String key ="";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().
                build(
                        ALiYunProperties.END_POINT,
                        ALiYunProperties.ACCESS_KEY_ID,
                        ALiYunProperties.ACCESS_KEY_SECRET
                );
        try {


            InputStream inputStream = file.getInputStream();

            // 创建PutObject请求。
            url = UUID.randomUUID().toString().replaceAll("-", "") + "-"+file.getOriginalFilename();
            String format = "专业实习2-mallImg/"+DateUtil.format( DateUtil.date(), "yyyy/MM/dd");
            key = format +"/"+ url;

            ObjectMetadata objectMetadata = new ObjectMetadata();

            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(ALiYunProperties.BUCKET_NAME, key, inputStream, objectMetadata);

            ossClient.putObject(putObjectRequest);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
                System.out.println("https://"+ALiYunProperties.BUCKET_NAME+"."+ALiYunProperties.END_POINT+"/"+key);
            }
        }
        return "https://"+ALiYunProperties.BUCKET_NAME+"."+ALiYunProperties.END_POINT+"/"+key;
    }
}
